app.factory("googlemap", ['$q', "$window", "LazyService", function ($q, $window, lazy) {
    function GoogleMapService() {
        this.apikey = "AIzaSyDFwH_IHBs_NAQkRx2LGCSYAK81UKWEAaU";
        this.map = null;
    }
    GoogleMapService.prototype = {
        init: function (element, lng, lat, zoom) {
            var self = this;
            return self.load().then(function () {
                var options = {
                    zoom: 12,
                    center: new google.maps.LatLng(lat, lng)
                };
                self.map = new google.maps.Map(element, options);
            });
        },
        load: function () {
            var deferred = $q.defer();
            $window.initializeGoogleMap = function () {
                deferred.resolve();
            };
            return lazy.js("https://maps.googleapis.com/maps/api/js?sensor=false&callback=initializeGoogleMap").then(function () {
                //console.log("lazy completed wait initializeGoogleMap !");
                return deferred.promise;
            });
        },
        addMarker: function (lng, lat) {
            var self = this;
            var marker = new google.maps.Marker({
                map: self.map,
                draggable: true,
                animation: google.maps.Animation.DROP,
                position: new google.maps.LatLng(lat, lng)
            });
            return marker;
        },
        addShop: function (shop) {
            var self = this;
            var marker = self.addMarker(shop.location.loc.coordinates[0], shop.location.loc.coordinates[1]);
            var infowindow = new google.maps.InfoWindow({
                content: '\
<div>\
    <a href="#shop/' + shop.login + '">@' + shop.login + '</a>\
    <p>' + shop.description + '</p>\
</div>'
            });

            google.maps.event.addListener(marker, 'click', function () {
                infowindow.open(self.map, marker);
            });

            return marker;
        },
        addHome: function (shop) {
            var self = this;
            var marker = self.addMarker(shop.location.loc.coordinates[0], shop.location.loc.coordinates[1]);
            var infowindow = new google.maps.InfoWindow({
                content: '\
<div>\
    <p>Mon adresse</p>\
</div>'
            });

            google.maps.event.addListener(marker, 'click', function () {
                infowindow.open(self.map, marker);
            });

            return marker;
        }
    }
    return new GoogleMapService();
} ]);

